<?php
/**
 * 秒杀控制器
 * @version 2015101415
 * @author Justin <justin@jipu.com> & <ezhu@jipukeji.com>
 */

namespace Shop\Controller;
use Think\Cache;

class SeckillController extends CommonController{
    function _before_index_display(&$lists){
        foreach($lists as &$vo){
            $item_ids_arr = str2arr($vo['item_ids']);
            foreach($item_ids_arr as $item){
                $vo['item_info'][] = get_item_info($item);
            }
        }
    }
    /**
     * 加入redis缓存
     */
    public function setRedisData($data){
        $redis = Cache::getInstance('Redis');
        $redis->set('invoice_'.$data['id'],$data);
    }
    public function index(){
        $act_id = I('act_id');
        $map['act_id'] =I('get.act_id');
        $map['store_id'] = $this->store_id;
        $map['status'] = array('in',array(-2,1,2,3));
        $order = 'id desc';
        $lists = $this->lists(CONTROLLER_NAME, $map,$order);
        if($lists){
            $start_time = M('SeckillActivity')->where(array('id'=>$act_id))->getField('start_time');
            $expire_time = M('SeckillActivity')->where(array('id'=>$act_id))->getField('expire_time');
            $lists[0]['start_time'] = $start_time;
            $lists[0]['expire_time'] = $expire_time;
        }
        int_to_string($lists, array('status' => array('0' => '<span class="text-cancel">已禁用</span>', '1' => '<span class="text-success">正常</span>')));
        //display前置操作
        method_exists($this, '_before_index_display') && $this->_before_index_display($lists);
        $this->assign('act_id',$act_id);
        $this->lists = $lists;
        $this->display();
     //   $this->assign('act_id',$act_id);
     //   parent::index($map);
    }
    public function activity(){
        $map['status'] = 1;
        $lists = M('SeckillActivity')->where($map)->order('id desc')->select();
        //dump($lists);die;
        $store_id = $_SESSION['jipushop_store']['seller_user']['store_id'];
        $store_grade = M('Store')->where(array('store_id' => $store_id))->getField('grade_id');
        $time = time();
        foreach ($lists as $k => $val) {
            $where['act_id'] = $val['id'];
            // $map1['act_id'] = $val['id'];
            $where['status'] = array('in', array(1, -2,2,3));
            $where['store_id'] = $store_id;
            $list = M('Seckill')->where($where)->order('id asc')->select();
            // dump($list);die;
            if ($list) {
                $lists[$k]['seckill_status'] = $list[0]['status'];
            } else {
                $lists[$k]['seckill_status'] = 0;
            }

            if ($store_grade == $val['store_grade'] || in_array($store_grade, explode(',', $val['store_grade']))) {
                $lists[$k]['grade'] = '1';
            } else {
                $lists[$k]['grade'] = '0';
            }
            $lists[$k]['activity_status'] = $val['expire_time'] < $time ? '-2' : '1';
            if ($lists[$k]['activity_status'] == -2) {
                M('Seckill')->where($where)->setField('status', -2);
                foreach ($list as $key => $value) {
                    $map1['seckill_id'] = $value['id'];
                    $map1['status'] = 1;
                    M('SeckillItem')->where($map1)->setField('status', -2);
                }
            } else {
                $where1['act_id'] = $val['id'];
                $where1['status'] = -2;
                M('Seckill')->where($where1)->setField('status', 1);
                foreach ($list as $key => $value) {
                    $map2['seckill_id'] = $value['id'];
                    $map2['status'] = -2;
                    M('SeckillItem')->where($map2)->setField('status', 1);
                }
            }
        }
          //  dump($lists);die;
            $this->assign('lists', $lists);
            $this->display();
        }

    public function setStatuss(){
        $ids = I('request.ids');
        $status = I('request.status');
        if(empty($ids)){
            $this->error('请选择要操作的数据');
        }
        $map['id']  = array('in',$ids);
        $data['status'] = $status;
        if($status == 1 ){
            $target   = M('Seckill')->where($map)->getField('item_ids');
            if($target){
                $need    = explode(',' , $target);
                $num     = count($need) ;
                $result  = M('Seckill')->where('status=1 and id !='.$ids)->getField('item_ids' ,true);
                if($result){
                    foreach($result as $k => $v){
                        $needs = explode(',' , $v);
                        $nums  = count($needs);
                        $temp  = array_unique(array_merge($needs , $need)) ;
                        $lastnum = count($temp);
                        if($nums + $num != $lastnum){
                            $this->error('同样的商品不能在活动中同时出现');
                            exit();
                        }
                    }
                }
            }
        }
        M('Seckill')->where($map)->save($data) ? $this->success('操作成功') : $this->error('操作失败');
    }


    public function add(){
        $activity_status = I('activity_status');
        if($activity_status == -2){
            $this->error('活动已过期，不能报名');
        }
        parent::add();
    }

    
    public function update(){
        $model = D('Seckill');
        $data['act_id'] = I('get.act_id');
        $data['store_id'] = $_SESSION['jipushop_store']['seller_user']['store_id'];
        $item_num = I('item_num');
        $data = $model->create();
        $status = M('Seckill')->where(array('id'=>$data['id']))->getField('status');
        if($status == 1){
            $this->error('已参加秒杀活动，不能编辑商品');
        }
        $num = count(explode(',',$data['item_ids']));
        if($num > $item_num){
           $this->error('上传商品数已超过最大商品数');
       }
        $model->startTrans();
        if($data && false !== $rst = $model->update($data)){
            //操作秒杀产品表
            $itemIds = getUniqure(explode(',',$data['item_ids']));
            $newArr = array();
            if($data['id']){
              //  修改秒杀商品信息
                $itemData = M('SeckillItem')->where(array('seckill_id'=>$data['id'],'status'=>array('in',array(1,2,3))))->field('item_id,seckill_id')->select();
                $oldIds = array_column($itemData, 'item_id');
                $i = 0;
                foreach ($itemIds as $key=>$val){
                    if(!in_array($val,$oldIds)){
                        $newArr[$i]['item_id'] = $val;
                        $newArr[$i]['seckill_id'] = $data['id'];
                        $newArr[$i]['stime'] = $data['start_time'];
                        $newArr[$i]['etime'] = $data['expire_time'];
                        $i++;
                    }
                }
                $delMap['seckill_id'] = array('eq',$data['id']);
                $delMap['item_id'] = array('not in',$itemIds);
                M('SeckillItem')->where($delMap)->delete();
                //更新参加秒杀时的商品
                $saveData['stime'] = $data['start_time'];
                $saveData['etime'] = $data['expire_time'];
                M('SeckillItem')->where(array('seckill_id'=>$data['id']))->save($saveData);
            }else{
               // 添加秒杀商品
                foreach ($itemIds as $key => $val){
                    $price = M('Item')->where(array('id'=>$val))->getField('price');
                    $stock = M('Item')->where(array('id'=>$val))->getField('stock');
                    $newArr[$key]['item_id'] = $val;
                    $newArr[$key]['seckill_id'] = $rst;
                    $newArr[$key]['stime'] = $data['start_time'];
                    $newArr[$key]['etime'] = $data['expire_time'];
                    $newArr[$key]['item_price'] = $price;
                    $newArr[$key]['item_stock'] = $stock;
                }
            }
            if(count($newArr)){
                $resAdd = M('SeckillItem')->addAll($newArr);
                if(!$resAdd){
                    $model->rollback();
                    $this->error('添加秒杀商品失败');
                }
            }
            $model->commit();
            $this->success('操作成功！', U('Seckill/index?act_id='.$data['act_id']));
        }else{
            $error = $model->getError();
            $model->rollback();
            $this->error(empty($error) ? '系统错误！' : $error);
        }
        parent::update();
    }

    public function itemList(){
        $item_ids = I('id');
        if(empty($item_ids))$this->error('活动ID不能为空');
        $seckillData = D('Seckill')->detail($item_ids);
        $map['m.status'] = array('eq', 1);
        $map['j.status'] = array('egt', 0);
        $map['j.seckill_id'] = array('eq', $item_ids);
        $prefix = C('DB_PREFIX');
        $l_table = $prefix.'seckill_item';
        $r_table = $prefix.'item';
        $model = M()->table($l_table.' j')->join($r_table.' m ON j.item_id = m.id');
        $field = 'm.images,m.supplier_id,m.name,m.price,m.stock,j.item_id as id,j.item_price,j.status';
        $order = 'j.item_id DESC';
        $limit = 10;
        $list = $this->lists($model, $map, $order, $field, $limit, null);
      // dump($list);die;
        int_to_string($list);
        Cookie('__forward__', $_SERVER['REQUEST_URI']);
        $this->assign('data', $seckillData);
        $this->assign('list', $list);
        $this->meta_title = '秒杀商品列表';
        $this->display();
    }

    public function editItem(){
            $id = I('id');
            $seckillId = I('seckill_id');
            if(empty($id) || empty($seckillId)) $this->error('参数异常');
            $prefix = C('DB_PREFIX');
           $seckillItemMode = $prefix.'seckill_item';
            $seckillItemSpecMode = $prefix.'seckill_item_spec';
            $itemModel = $prefix.'item';
            $model = M('seckill j')->join(' INNER JOIN '.$seckillItemMode.' m ON j.id = m.seckill_id ')
                ->join(' LEFT JOIN '.$seckillItemSpecMode.' s ON s.item_id = m.item_id ')
                ->join(' LEFT JOIN '.$itemModel.' i ON i.id=m.item_id');
            $map['m.item_id'] = array('eq',$id);
            $map['m.seckill_id'] = array('eq',$seckillId);
             $map['j.status'] = array('gt',0);
            $field = 'j.id as seckill_id,m.item_id,m.item_price as oprice,m.item_stock as ostock,s.spc_code,i.cid_1,i.cid_2,i.cid_3,i.name';
            $data = $model->where($map)->field($field)->find();
       // var_dump($data);die;
        $data['prop_info'] = json_decode($data['prop_info'],true);
            $this->data = $data;
          //  dump($data);die;
            $this->display();
    }

    public function editItemHandle(){
        $Model = D('SeckillItem');
        $item_id = I('item_id');
        $stock = M('Item')->where(array('id'=>$item_id))->getField('stock');
        $data = I('post.');
        if($data['item_stock'] > $stock){
            $this->error('库存不能大于商品总库存');
        }
        $status = M('Seckill')->where(array('id'=>$data['seckill_id']))->getField('status');
       if($status == 1){
            $this->error('已通过平台审核，不能修改商品价格');
        }
        $Model->startTrans();
        $res = $Model->update();
     //   dump($res);exit;
        if($res !== false){
            $rst = $this->saveSpecifiction($item_id);
          //  dump($rst);die;
            if($rst !== false){
                $Model->commit();
                $this->success('更新成功' , U('Seckill/itemList' ,array('id' => $_POST['seckill_id'])));
            }else{
                $Model->rollback();
                $this->error('更新失败');
            }
        }else{
            $Model->rollback();
            $this->error($Model->getError());
        }
    }


    public function saveSpecifiction($item_id = null){
     //  dump($_POST);die;
        if(empty($item_id)){
            return false;
        }
        //实例化商品规格模型
        $ItemSpecifiction = M('SeckillItemSpec');
        //获取库存数量数组
        $spc_quantity = I('spc_quantity');
        $activity_id  = I('seckill_id');
        //获取价格数组
       $item_price = I('item_pri');
       //生成规格组合值数组
        $total_quantity = 0;
        foreach($spc_quantity as $key => $val){
            if(!empty($val)){
                $spcItem[] = array(
                    'item_id' => $item_id,
                    'spc_code'  => $key,
                    'quantity'  => $val,
                    'item_price'  => $item_price[$key],
                    'activity_id' => $activity_id ,

                );
                //计算总库存
                $total_quantity += $spc_quantity[$key];
            }

        }
         $spe = M('ItemSpecifiction')->where(array('item_id'=>$item_id))->select();
        if($spe){
            if(!$spcItem){
                $this->error('请填写商品规格价格');
            }
        }
        //清空旧的规格数据
        $result = $ItemSpecifiction->where('item_id='.$item_id.' and activity_id='.$activity_id)->delete();
        if($result !== false){
            //规格组合信息批量写入
            if(!empty($spcItem)){
                if($result = $ItemSpecifiction->addAll($spcItem)){
                    //更新总库存
                    $result = M('SeckillItem')->where(array('item_id'=>$item_id ,'seckill_id' => $activity_id))->setField('item_stock', $total_quantity);
                }
            }
        }
       // $result ? $this->success('保存成功') : $this->error('保存失败');
            return $result;
    }


    public function setItemStatus(){
        $ids = (array)I('request.ids');
        $seckillId = I('request.seckill_id');
        $status = I('request.status');
        if(empty($ids) || empty($seckillId)){
            $this->error('请选择要操作的数据');
        }
        $seckillData = M('Seckill')->where(array('id'=>$seckillId))->find();
        $seckillItemIds = explode(',',$seckillData['item_ids']);
        $model = M('SeckillItem');
        $map['item_id'] = array('in',$ids);
        $map['seckill_id'] = array('eq',$seckillId);
        $model->startTrans();
        switch ($status){
            case -1 ://删除
                $rst = $model->where($map)->delete();
                if($rst !== false){
                    $rst = $this->delItemIds($seckillId,$seckillItemIds,$ids);
                    if($rst !== false){
                        $model->commit();
                        $this->success('删除成功','',IS_AJAX);
                    }else{
                        $model->rollback();
                        $this->error('删除失败','',IS_AJAX);
                    }
                }else{
                    $model->rollback();
                    $this->error('删除失败','',IS_AJAX);
                }
                break;
            case 0  :  //禁用
                $rst = $model->where($map)->save(array('status'=>$status));
                if($rst !== false){
                    $model->commit();
                    $this->success('禁用成功','',IS_AJAX);
                }else{
                    $model->rollback();
                    $this->error('禁用失败','',IS_AJAX);
                }
                break;
            case 1  :  //上架
                $rst = $model->where($map)->save(array('status'=>$status));
                if($rst !== false){
                    $model->commit();
                    $this->success('启用成功','',IS_AJAX);
                }else{
                    $model->rollback();
                    $this->error('启用失败','',IS_AJAX);
                }
                break;
            default:
                $model->rollback();
                $this->error('系统参数错误');
                break;

        }
    }

    public function delItemIds($id,$itemIds,$newIds){
        $newArr = array();
        foreach ($itemIds as $key=>$val){
            if(!in_array($val,$newIds)){
                array_push($newArr,$val);
            }
        }
        $Ids = implode(',',$newArr);
        $rst = M('Seckill')->where(array('id'=>$id))->save(array('item_ids'=>$Ids));
        return $rst;
    }

    public function ajaxProp($item_id = null, $type = null, $cid_1 = null, $cid_2 = null, $cid_3 = null ,$activity_id = null){
        $where['type'] = $type;
        if(!empty($cid_1)){
            $cid[0] = $cid_1;
        }

        if(!empty($cid_2)){
            $cid[1] = $cid_2;
        }

        if(!empty($cid_3)){
            $cid[2] = $cid_3;
        }

        $where['cid'] = array('in',$cid);
        $where['a.item_id'] = array('eq',$item_id);
        $where['b.type'] = array('eq','specification');

        //获取该商品的属性值和关联的属性项信息（关联模型不能用从表的字段排序，用原生sql代替）
        $prefix = C('DB_PREFIX');
        $l_table = $prefix.'item_extend';
        $r_table = $prefix.'item_property';
        $field = 'b.type, b.cname, b.ename, b.displayorder, b.formtype, a.*';
        $order = 'b.displayorder asc, b.id asc';
        $model = M()->table($l_table.' a')->join($r_table.' b ON a.prp_id = b.id');
        $property_list = $model->where($where)->field($field)->order($order)->select();
//         $sql = 'select '.$field .' from '.$l_table.' a, '.$r_table.' b where a.item_id = '.$item_id.' AND a.prp_id = b.id '.$order;
//         $property = M()->query($sql);
        //获取规格组合数据
        $spc_data = null;
        $propVal = array();
        if(!empty($item_id)){
            $field = 'spc_code,quantity,item_price';
            $spc_info = M('seckill_item_spec')->where('item_id = '.$item_id.' and activity_id='.$activity_id)->field($field)->select();
          //  $spc_info = M('item_specifiction')->where('item_id = '.$item_id)->field($field)->select();

            if(!empty($spc_info)){
                $spc_data = json_encode($spc_info);
                foreach ($spc_info as $key=>$val){
                    $propVal = array_merge($propVal,explode('-',$val['spc_code']));
                }
            }
        }
        //拼接属性名称，属性选项配置，属性值数组
        if($property_list){
            foreach($property_list as $list) {
                $property_all[$list['id']]['property'] = $list;
                $property_all[$list['id']]['option'] = D('Seckill')->getOptionValue(unserialize($list['info']),$list['type']);
                $property_all[$list['id']]['value'] = $propVal;
                //$property_all[$list['id']]['pic'] = $this->getValue($item_id, $list['id'], 'pic', $type, $list['formtype']);
            }
        }
        $this->assign('item_id', $item_id);
        $this->assign('type', $type);
        $this->assign('property_all', $property_all);
        $this->assign('spc_data', $spc_data);
        $this->display();
    }



}

